package com.hut.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hut.oa.common.GeetestLib;
import com.hut.oa.model.bean.Menu;
import com.hut.oa.model.bean.Role;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.dao.announce.AnnounceDao;
import com.hut.oa.model.dao.announce.AnnounceUserDao;
import com.hut.oa.model.dao.apply.ApplyDao;
import com.hut.oa.model.dao.scedule.SceduleDao;
import com.hut.oa.model.dao.system.MenuDao;
import com.hut.oa.model.dao.task.TaskDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.model.dao.workattend.WorkAttendDao;
import com.hut.oa.service.SystemService;

@Controller
@RequestMapping("/oa")
public class MainController {
	Logger log=LoggerFactory.getLogger(getClass());
	
	@Autowired
	SystemService ss;
	
	@Autowired
	MenuDao md;
	
	@Autowired
	UserDao ud;
	
	@Autowired
	AnnounceUserDao aud;
	
	@Autowired
	WorkAttendDao wad;
	
	@Autowired
	SceduleDao sd;
	
	@Autowired
	AnnounceDao ad;
	
	@Autowired
	ApplyDao applydao;
	
	@Autowired
	TaskDao tdao;
	/**
     * 超级管理员id
     */
    @Value("${system.superid}")
    Long superId;
	
	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String toLogin(){
		return "login";
	}
	
	/**
	 * 验证登录
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String loginCheck(User user,Model model,HttpSession session){
		User loginUser=ud.findByName(user.getName());
		if(loginUser!=null && user.getPassword().equals(loginUser.getPassword())){
			//登录成功，存入session
			session.setAttribute("userinfo", loginUser);
			session.setMaxInactiveInterval(60*60*3);//设置失效时长为一小时
			log.info("登录成功： {}", loginUser);
			
			List<Menu> resources=new ArrayList<>();//所有资源
			List<Menu> menus=new ArrayList<>();//菜单
			List<Menu> operates=new ArrayList<>();//操作
			List<Role> roles=loginUser.getRoles();
			for (Role role : roles) {
				resources.addAll(role.getMenus());
			}
			session.setAttribute("types", ss.getTypes());
			session.setAttribute("status", ss.getStatus());
			//判断是不是超管
			if(superId==loginUser.getId()){
				menus=md.findByOpenAndTypeOrderBySeq(true,"menu");
				operates=md.findByOpenAndTypeOrderBySeq(true,"operate");
			}else{
				for (Menu resource : resources) {
					if("menu".equals(resource.getType()) && resource.isOpen()){
						boolean flag=true;//去除重复
						for (Menu menu : menus) {
							if(menu.getId()==resource.getId()){
								flag=false;
								break;
							}
						}
						if(flag){
							menus.add(resource);
						}
					}else if("operate".equals(resource.getType())){
						operates.add(resource);
					}
				}
			}
			log.info("可用菜单： {}", menus);
			log.info("可用权限： {}", operates);
			session.setAttribute("menus", menus);
			session.setAttribute("operates", operates);
			return "redirect:/oa/main";
		}else{
			model.addAttribute("error", "用户名或密码错误， 登录失败");
			log.info("登录失败： {}", loginUser);
			return "login";
		}
	}
	
	/**
	 * 加载验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/captcha")
	@ResponseBody
	public void loginCaptchaCreate(HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		GeetestLib gtSdk = new GeetestLib("b46d1900d0a894591916ea94ea91bd2c", "36fc3fe98530eea08dfc6ce76e3d24c4",false);
        String resStr = "{}";
        //进行验证预处理

        int gtServerStatus = gtSdk.preProcess();

        //将服务器状态设置到session中

        request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);//放入session，用于后面的验证
        resStr = gtSdk.getResponseStr();
        PrintWriter out = response.getWriter();

        out.println(resStr);
	}
	
	/**
	 * 二次验证验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value="/captcha",method=RequestMethod.POST)
	public void loginCaptchaCheck(HttpServletRequest request,HttpServletResponse response) throws IOException{
		GeetestLib gtSdk = new GeetestLib("b46d1900d0a894591916ea94ea91bd2c", "36fc3fe98530eea08dfc6ce76e3d24c4",false);
		
		String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
		String validate = request.getParameter(GeetestLib.fn_geetest_validate);
		String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);
		
		//从session中获取gt-server状态
		int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
		
		//从session中获取userid
		String userid = (String)request.getSession().getAttribute("userid");
		
		int gtResult = 0;
		PrintWriter out = response.getWriter();
		if (gt_server_status_code == 1) {
			//gt-server正常，向gt-server进行二次验证
				
			gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, userid);
			out.println(gtResult);
		} else {
			// gt-server非正常情况下，进行failback模式验证
				
			System.out.println("failback:use your own server captcha validate");
			gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
			out.println(gtResult);
		}
	}
	
	/**
	 * 退出登录
	 * @param session
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		//移除session
		session.removeAttribute("userinfo");
		return "redirect:/oa/login";
	}
	
	/**
	 * 主页面
	 * @return
	 */
	@RequestMapping("/main")
	public String toMain(Model model,HttpSession session){
		User user=(User) session.getAttribute("userinfo");
		//公告
		model.addAttribute("ann",  ad.findByType(0));
		
		//审批
		model.addAttribute("applys",applydao.findByDeptOffice(user.getDeptOffice()));
		//任务
		model.addAttribute("tasklist", tdao.findByUser(user));
		//今日签到记录
		model.addAttribute("sign", wad.finByuidtypeto("签到", user.getId()));
		//今日签到记录
		model.addAttribute("signout", wad.finByuidtypeto("签退", user.getId()));
		//日历
		model.addAttribute("calendar",sd.findByUserId(user.getId()));
		//未读通知数
		model.addAttribute("noticeCount", aud.noReadCount(user));
		return "main_frame";
	}
	
	/*@RequestMapping("/webtest")
	public String treeData() {
		return "test";
	}*/
	
}
